package com.wqiuqiu.gulimall.member.service.impl;

import com.wqiuqiu.common.R;
import com.wqiuqiu.common.constant.MemberConstant;
import com.wqiuqiu.common.excption.BizCodeEnume;
import com.wqiuqiu.common.to.login.AccountTo;
import com.wqiuqiu.common.to.thridservice.Oauth2To;
import com.wqiuqiu.gulimall.member.entity.MemberLevelEntity;
import com.wqiuqiu.gulimall.member.exception.UserRegException;
import com.wqiuqiu.gulimall.member.service.MemberLevelService;
import com.wqiuqiu.gulimall.member.vo.RegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wqiuqiu.common.PageUtils;
import com.wqiuqiu.common.Query;

import com.wqiuqiu.gulimall.member.dao.MemberDao;
import com.wqiuqiu.gulimall.member.entity.MemberEntity;
import com.wqiuqiu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void memberReg(RegisterVo vo) throws UserRegException{
        //TODO 验证邮箱和用户名是否已经存在
        MemberEntity username = this.getOne(new QueryWrapper<MemberEntity>().eq("username", vo.getUserName()));
        if (username != null){
            throw new UserRegException("用户名已经存在");
        }
        MemberEntity email = this.getOne(new QueryWrapper<MemberEntity>().eq("email", vo.getEamil()));
        if (email != null){
            throw new UserRegException("邮箱已经存在");
        }
        Long defalutMemberLevel = getDefalutMemberLevel();
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setEmail(vo.getEamil());

        //加密 数据库存储的密码值是经过盐值加密之后
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setLevelId(defalutMemberLevel);

        this.save(memberEntity);

        //
    }

    private Long getDefalutMemberLevel() {
        return memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1)).getId();
    }

    @Override
    public MemberEntity oauth2Login(Oauth2To oauth2To) {
        MemberEntity entity;
        //查询该id是否绑定本网站用户，如果有，就返回本网站的用户信息，没有就先注册一个
        MemberEntity social_uid = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", oauth2To.getId()));
        if (social_uid != null){
            entity = social_uid;
        }else {
            //需要注册
            entity = new MemberEntity();
            entity.setSocialUid(oauth2To.getId());
            entity.setLevelId(getDefalutMemberLevel());
            entity.setUsername(oauth2To.getName());
            entity.setNickname(oauth2To.getLogin());
            //初始默认密码
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encode = encoder.encode(MemberConstant.DEFALUT_PASSWORD);
            entity.setPassword(encode);
            if (StringUtils.isNotEmpty(oauth2To.getEmail())){
                //TODO 是否还要验证一下邮箱格式
                entity.setEmail(oauth2To.getEmail());
            }
            entity.setCreateTime(new Date(System.currentTimeMillis()));
            this.save(entity);
        }
        return entity;
    }

    @Override
    public R gulimallLogin(AccountTo to) {
        String user = to.getUsername();
        MemberEntity one = this.getOne(new QueryWrapper<MemberEntity>().eq("username", user).or().eq("mobile", user).or().eq("email", user));
        if (one != null){
            //密码匹配
            String password = one.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(to.getPassword(), password);
            if (matches){
                return R.ok().setData(one);
            }else {
                return R.error(BizCodeEnume.USER_PASSWORD_EXCEPTION.getCode(),BizCodeEnume.USER_PASSWORD_EXCEPTION.getMessage());
            }
        }else {
            //没有此用户
            return R.error(BizCodeEnume.USER_NAME_EXCEPTION.getCode(),BizCodeEnume.USER_NAME_EXCEPTION.getMessage());
        }
    }


}